package com.java.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 线程池
 */
public class ThreadPoolExecutorTests {
    /**核心线程数*/
    static int corePoolSize=2;
    /**最大线程数*/
    static int maximumPoolSize=3;
    /**空闲线程释放时间*/
    static int keepAliveTime=60;
    /**阻塞式任务队列*/
    static BlockingQueue<Runnable> workQueue=new ArrayBlockingQueue<>(1);
    /**创建线程的工厂*/
    private static AtomicLong atomicLong=new AtomicLong(1);
    static ThreadFactory threadFactory=new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "tedu-2305-"+atomicLong.getAndIncrement());
        }
    };
    /**拒绝策略：
     * 1)AbortPolicy 直接拒绝，抛出异常
     * 2)DiscardPolicy 直接丢弃
     * 3)callerRunsPolicy 由调用者线程执行。
     * 4)DiscardOldestPolicy 丢弃队列中最早放入的任务，将当前任务交给线程池。
     * */
    static RejectedExecutionHandler handler=
            new ThreadPoolExecutor.AbortPolicy();


    public static void main(String[] args) {
        //企业中推荐使用的线程池对象
        ThreadPoolExecutor poolExecutor=
         new ThreadPoolExecutor(//-7大入参
                 corePoolSize,//1.核心线程数量,池中线程数量小于这个值时,每来一个任务都会创建一个新的线程
                 maximumPoolSize,//3.最大线程数,核心线程在忙,队列也满了,再来新的任务,则创建新线程
                 keepAliveTime,//具体空闲时间
                 TimeUnit.SECONDS,//时间单位
                 workQueue,//2.当核心线程忙时,再来新的任务,可以放到阻塞队列
                 threadFactory,//负责创建线程
                 handler
                 );//拒绝策略
        //执行任务
        poolExecutor.execute(()->{//Runnable
            String threadName=Thread.currentThread().getName();
            System.out.println(threadName+"->"+"task1");
            try{Thread.sleep(500);}catch (Exception e){}
        });
        poolExecutor.execute(()->{//Runnable
            String threadName=Thread.currentThread().getName();
            System.out.println(threadName+"->"+"task2");
            try{Thread.sleep(500);}catch (Exception e){}
        });
        poolExecutor.execute(()->{//Runnable
            String threadName=Thread.currentThread().getName();
            System.out.println(threadName+"->"+"task3");
            try{Thread.sleep(500);}catch (Exception e){}
        });
        poolExecutor.execute(()->{//Runnable
            String threadName=Thread.currentThread().getName();
            System.out.println(threadName+"->"+"task4");
            try{Thread.sleep(500);}catch (Exception e){}
        });
        poolExecutor.execute(()->{//Runnable
            String threadName=Thread.currentThread().getName();
            System.out.println(threadName+"->"+"task5");
            try{Thread.sleep(500);}catch (Exception e){}
        });

        //关闭线程池(实际项目中是服务停止时关闭池,例如停掉tomcat)
        poolExecutor.shutdown();
    }

}
